<template>
    <div class="bill-of-material-container">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
            <span>首页</span>
            <span class="separator">/</span>
            <span>物料清单</span>
            <el-icon class="close-icon" @click="$router.go(-1)">
                <Close />
            </el-icon>
        </div>

        <!-- 标题 -->
        <div class="page-title">
            <el-icon>
                <Box />
            </el-icon>
            <span>物料清单管理</span>
        </div>

        <!-- 搜索和操作区域 -->
        <div class="search-action-bar">
            <div class="search-fields">
                <el-input v-model="searchForm.parentProductCode" placeholder="父项产品编号" clearable
                    style="width: 200px; margin-right: 10px;" />
                <el-input v-model="searchForm.parentProductName" placeholder="父项产品名称" clearable
                    style="width: 200px; margin-right: 10px;" />
                <el-input v-model="searchForm.childProductCode" placeholder="子项产品编号" clearable
                    style="width: 200px; margin-right: 10px;" />
                <el-input v-model="searchForm.childProductName" placeholder="子项产品名称" clearable
                    style="width: 200px; margin-right: 10px;" />
            </div>
            <div class="action-buttons">
                <el-button type="primary" @click="handleSearch">
                    <el-icon>
                        <Search />
                    </el-icon>
                    查询
                </el-button>
                <el-button @click="handleReset">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    重置
                </el-button>
                <el-button type="success" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新建
                </el-button>
                <el-button type="primary" @click="handleEdit" :disabled="!selectedRow">
                    <el-icon>
                        <Edit />
                    </el-icon>
                    编辑
                </el-button>
                <el-button type="danger" @click="handleDelete" :disabled="!selectedRow">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    删除
                </el-button>
                <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    批量删除
                </el-button>
            </div>
        </div>

        <!-- 主表格：物料清单列表 -->
        <div class="main-table">
            <el-table :data="billOfMaterialList" @row-click="handleRowClick" @selection-change="handleSelectionChange"
                highlight-current-row v-loading="loading" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="#" width="60" />
                <el-table-column prop="parentProductCode" label="父项产品编号" width="150" />
                <el-table-column prop="parentProductName" label="父项产品名称" width="200" />
                <el-table-column prop="childProductCode" label="子项产品编号" width="150" />
                <el-table-column prop="childProductName" label="子项产品名称" width="200" />
                <el-table-column prop="unitUsage" label="单位用量" width="120" />
                <el-table-column prop="remark" label="备注" width="200" show-overflow-tooltip />
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="creator" label="创建人" width="100" />
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click.stop="handleEdit(scope.row)">
                            <el-icon><Edit /></el-icon>
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click.stop="handleDelete(scope.row)">
                            <el-icon><Delete /></el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.pageIndex" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 30, 50, 100]" :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 物料清单编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑物料清单' : '新建物料清单'" width="800px" :close-on-click-modal="false"
            @close="handleDialogClose">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px"
                style="max-height: 600px; overflow-y: auto;">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="父项产品" prop="parentProductId">
                            <el-select v-model="form.parentProductId" placeholder="请选择父项产品" clearable style="width: 100%"
                                :loading="productLoading" filterable>
                                <el-option v-for="product in productOptions" :key="product.productId"
                                    :label="`${product.productCode} - ${product.productName}`" :value="product.productId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="子项产品" prop="childProductId">
                            <el-select v-model="form.childProductId" placeholder="请选择子项产品" clearable style="width: 100%"
                                :loading="productLoading" filterable>
                                <el-option v-for="product in productOptions" :key="product.productId"
                                    :label="`${product.productCode} - ${product.productName}`" :value="product.productId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="单位用量" prop="unitUsage">
                            <el-input-number v-model="form.unitUsage" :min="0.01" :precision="2" style="width: 100%"
                                placeholder="请输入单位用量" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        {{ isEdit ? '更新' : '创建' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    Close,
    Box
} from '@element-plus/icons-vue'
import {
    getBillOfMaterialList,
    getBillOfMaterialById,
    createBillOfMaterial,
    updateBillOfMaterial,
    deleteBillOfMaterial,
    batchDeleteBillOfMaterial,
    checkBillOfMaterialExists,
    getAllProductOptions,
    type BillOfMaterialDetailDTO,
    type BillOfMaterialCreateDTO,
    type BillOfMaterialUpdateDTO,
    type Product
} from '@/api/billOfMaterial'

// 响应式数据
const billOfMaterialList = ref<BillOfMaterialDetailDTO[]>([])
const selectedRow = ref<BillOfMaterialDetailDTO | null>(null)
const selectedRows = ref<BillOfMaterialDetailDTO[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const loading = ref(false)
const submitLoading = ref(false)
const productLoading = ref(false)

// 选项数据
const productOptions = ref<Product[]>([])

// 搜索表单
const searchForm = reactive({
    parentProductCode: '',
    parentProductName: '',
    childProductCode: '',
    childProductName: ''
})

// 分页数据
const pagination = reactive({
    pageIndex: 1,
    pageSize: 30,
    total: 0
})

// 表单数据
const form = reactive({
    billOfMaterialId: 0,
    parentProductId: undefined as number | undefined,
    childProductId: undefined as number | undefined,
    unitUsage: 1,
    remark: ''
})

// 表单验证规则
const rules = {
    parentProductId: [
        { required: true, message: '请选择父项产品', trigger: 'change' }
    ],
    childProductId: [
        { required: true, message: '请选择子项产品', trigger: 'change' }
    ],
    unitUsage: [
        { required: true, message: '请输入单位用量', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '单位用量必须大于0', trigger: 'blur' }
    ]
}

// 表单引用
const formRef = ref()

// 方法
const fetchData = async () => {
    try {
        loading.value = true
        const response = await getBillOfMaterialList({
            pageIndex: pagination.pageIndex,
            pageSize: pagination.pageSize
        })
        if (response.data.code === 200) {
            billOfMaterialList.value = response.data.pageData
            pagination.total = response.data.totalCount
        } else {
            ElMessage.error(response.data.msg || '获取物料清单列表失败')
        }
    } catch (error) {
        console.error('获取物料清单列表失败:', error)
        ElMessage.error('获取物料清单列表失败')
    } finally {
        loading.value = false
    }
}

const fetchProductOptions = async () => {
    try {
        productLoading.value = true
        const response = await getAllProductOptions()
        if (response.data.code === 200) {
            productOptions.value = response.data.data
        } else {
            ElMessage.error(response.data.msg || '获取产品选项失败')
        }
    } catch (error) {
        console.error('获取产品选项失败:', error)
        ElMessage.error('获取产品选项失败')
    } finally {
        productLoading.value = false
    }
}

const handleSearch = () => {
    pagination.pageIndex = 1
    fetchData()
}

const handleReset = () => {
    searchForm.parentProductCode = ''
    searchForm.parentProductName = ''
    searchForm.childProductCode = ''
    searchForm.childProductName = ''
    pagination.pageIndex = 1
    fetchData()
}

const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.pageIndex = 1
    fetchData()
}

const handleCurrentChange = (page: number) => {
    pagination.pageIndex = page
    fetchData()
}

const handleRowClick = (row: BillOfMaterialDetailDTO) => {
    selectedRow.value = row
}

const handleSelectionChange = (selection: BillOfMaterialDetailDTO[]) => {
    selectedRows.value = selection
}

const resetForm = () => {
    Object.assign(form, {
        billOfMaterialId: 0,
        parentProductId: undefined,
        childProductId: undefined,
        unitUsage: 1,
        remark: ''
    })
}

const handleAdd = () => {
    isEdit.value = false
    resetForm()
    dialogVisible.value = true
}

const handleEdit = (row?: BillOfMaterialDetailDTO) => {
    const targetRow = row || selectedRow.value
    if (!targetRow) {
        ElMessage.warning('请选择要编辑的物料清单')
        return
    }

    isEdit.value = true
    Object.assign(form, {
        billOfMaterialId: targetRow.billOfMaterialId,
        parentProductId: targetRow.parentProductId,
        childProductId: targetRow.childProductId,
        unitUsage: targetRow.unitUsage,
        remark: targetRow.remark || ''
    })
    dialogVisible.value = true
}

const handleDelete = async (row?: BillOfMaterialDetailDTO) => {
    const targetRow = row || selectedRow.value
    if (!targetRow) {
        ElMessage.warning('请选择要删除的物料清单')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除物料清单 "${targetRow.parentProductName} -> ${targetRow.childProductName}" 吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const response = await deleteBillOfMaterial(targetRow.billOfMaterialId, 'Admin')
        if (response.data.code === 200) {
            ElMessage.success('删除成功')
            if (selectedRow.value?.billOfMaterialId === targetRow.billOfMaterialId) {
                selectedRow.value = null
            }
            fetchData()
        } else {
            ElMessage.error(response.data.msg || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除物料清单失败:', error)
            ElMessage.error('删除物料清单失败')
        }
    }
}

const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的物料清单')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 个物料清单吗？`,
            '确认批量删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const billOfMaterialIds = selectedRows.value.map(row => row.billOfMaterialId)
        const response = await batchDeleteBillOfMaterial(billOfMaterialIds, 'Admin')
        if (response.data.code === 200) {
            ElMessage.success('批量删除成功')
            selectedRows.value = []
            selectedRow.value = null
            fetchData()
        } else {
            ElMessage.error(response.data.msg || '批量删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除物料清单失败:', error)
            ElMessage.error('批量删除物料清单失败')
        }
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        if (isEdit.value) {
            const updateData: BillOfMaterialUpdateDTO = {
                billOfMaterialId: form.billOfMaterialId,
                parentProductId: form.parentProductId!,
                childProductId: form.childProductId!,
                unitUsage: form.unitUsage,
                remark: form.remark || undefined,
                modifier: 'Admin'
            }

            const response = await updateBillOfMaterial(updateData)
            if (response.data.code === 200) {
                ElMessage.success('更新成功')
                dialogVisible.value = false
                fetchData()
            } else {
                ElMessage.error(response.data.msg || '更新失败')
            }
        } else {
            const createData: BillOfMaterialCreateDTO = {
                parentProductId: form.parentProductId!,
                childProductId: form.childProductId!,
                unitUsage: form.unitUsage,
                remark: form.remark || undefined,
                creator: 'Admin'
            }

            const response = await createBillOfMaterial(createData)
            if (response.data.code === 200) {
                ElMessage.success('创建成功')
                dialogVisible.value = false
                fetchData()
            } else {
                ElMessage.error(response.data.msg || '创建失败')
            }
        }
    } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage.error('操作失败')
    } finally {
        submitLoading.value = false
    }
}

const handleDialogClose = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    resetForm()
    isEdit.value = false
}

// 工具方法
const formatDateTime = (dateTime: string | undefined) => {
    if (!dateTime) return ''
    return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
    fetchData()
    fetchProductOptions()
})
</script>

<style scoped>
.bill-of-material-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.breadcrumb {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 14px;
    color: #666;
}

.breadcrumb .separator {
    margin: 0 8px;
    color: #ccc;
}

.breadcrumb .close-icon {
    margin-left: auto;
    cursor: pointer;
    color: #999;
}

.breadcrumb .close-icon:hover {
    color: #409eff;
}

.page-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

.page-title .el-icon {
    margin-right: 8px;
    font-size: 24px;
    color: #409eff;
}

.search-action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-fields {
    display: flex;
    align-items: center;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.main-table {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.pagination-container {
    display: flex;
    justify-content: center;
    padding: 20px;
    background-color: white;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .search-action-bar {
        flex-direction: column;
        gap: 15px;
    }

    .search-fields {
        flex-wrap: wrap;
        gap: 10px;
    }

    .action-buttons {
        flex-wrap: wrap;
        justify-content: center;
    }
}
</style>
